<?php
/**
 * Created by 橙橙同学.
 * User: 橙橙同学
 * Date: 2017/11/13
 * Time: 下午10:49
 */
namespace app;
/**
 * Class ParkTemplateMessage
 * @package app
 * 停车场模板消息推送者
 */
class ParkTemplateMessager{

    const P_ENTRY = '3FHdIxzq-r24IBspWkrwAG29RiNRVa4PY2u1XxvWEAk'; // 会员入场
    const P_LEAVE = '6JAPro7VFgfX0G-nIX3dNTxRNawmxsMwKjoUe70jDKE'; // 会员离场
    const P_PARKING = 'Ngm7L8Ve88gnDNYGveq5jb96olZd-eV_UVXW54sYRNE'; //

    /**
     * @param $cardNum
     * @param $type
     * @param $json
     * @return mixed|string
     * @author:橙橙同学
     * @func:准备模板消息数据
     */
    public function prepareTemplateMessageData($cardNum, $type, $json)
    {

        $openid = self::getOpenidByCardNum($cardNum);
        if (!$openid) {
            if($type == 'P_PARKING'){
                $openid = array();
                $openid['openid'] = '';
                $openid['realname'] = '';
                $jsondata = json_decode($json, true);
                //@todo 添加JSON数据校验
                //$status = Check::checkParking($jsondata);

                // 非微信会员数据存储
                $currentTime = time();
                //当天的起止时间
                $y = date("Y");
                $m = date("m");
                $d = date("d");
                /**
                 * 当天的起止时间
                 */
                $day_start = mktime(0,0,0,$m,$d,$y);
                $day_end   = mktime(23,59,59,$m,$d,$y);

                /* 检测接口调用地址存储停车位置， 如果已经存在的话不发送数据 */
                // 1. 查询本地存存储的停车位置信息，如果存在不发送停车入位信息推送
                // 2. 本地不存在停车位信息，存储停车位置，并发送消息

                $parkNoStatus = self::db()->select('ims_parkinfo_status', 'parkno', array(
                    'AND' => array('platenumber'    => $cardNum,
                        'parkno'          =>  $json['parkingNo'],
                        'create_time[<>]' => array($day_start, $day_end),
                    )
                ),
                    array(
                        'ORDER'=> 'create_time DESC '
                    )
                );

                if(empty($parkNoStatus)){
                    $data = array(
                        'platenumber' => $cardNum,
                        'parkno'      => $jsondata['parkingNo'],
                        'park_img'    => $jsondata['parkingImg'],
                        'create_time' => time()
                    );
                    $insert_id = self::db()->insert('ims_parkinfo_status', $data);
                }
            }
            return json('0', '您输入的号码: ' . $cardNum . ' 未绑定微信');
        }

        // 根据消息类型返回相关字符串
        $typeFunc = '';
        switch ($type) {
            // 会员进场
            case 'P_ENTRY':
                $jsondata = json_decode($json, true);
                $status   = Check::checkEntry($jsondata);
                if ($status !== true) {
                    return json('0', $status);
                }
                $openid['entry_time'] = $jsondata['entryTime'];
                Park::setEntry($openid);
                $typeFunc = self::entry($openid, $jsondata);
                break;

            // 会员离场
            case 'P_LEAVE':
                $jsondata = json_decode($json, true);
                $status   = Check::checkLeave($jsondata);
                if ($status !== true) {
                    return json('0', $status);
                }
                $openid['leave_time'] = $jsondata['leaveTime'];
                $openid['score']      = $jsondata['score'];
                $openid['duration']   = $jsondata['duration'];
                $openid['amount']     = $jsondata['amount'];
                $openid['prestore']   = $jsondata['prestore'];
                Park::setLeave($openid);
                $typeFunc = self::leave($openid, $jsondata);
                break;

            // 积分消费
            case 'M_SCORE':
                $jsondata = json_decode($json, true);
                $status   = Check::checkScore($jsondata);

                if ($status !== true) {
                    return json('0', $status);
                }
                $typeFunc = self::score($openid, $jsondata);

                break;

            // 会员消费
            case 'O_ORDER':
                $jsondata = json_decode($json, true);
                $status   = Check::checkOrder($jsondata);

                if ($status !== true) {
                    return json('0', $status);
                }

                $typeFunc = self::order($openid, $jsondata);
                //return json('1', '暂停推送');
                break;
            // 成为会员
            case 'M_REG':
                $jsondata = json_decode($json, true);
                $status   = Check::checkReg($jsondata);
                if ($status !== true) {
                    return json('0', $status);
                }
                $typeFunc = self::Reg($openid['openid'], $jsondata);
                break;

            case 'P_PARKING':
                $jsondata = json_decode($json, true);

                $status = Check::checkParking($jsondata);
                if($status !== true){
                    return json('0', $status);
                }
                //@todo 使用停车位信息函数
                //self::parkingInfo($openid, $jsondata);
                $typeFunc = self::parkingInfo($cardNum, $openid, $jsondata);
                //return json('0','触发条件有误');
                break;
            default:
                return json('0', '类型不存在');
        }
        return $typeFunc;
    }


    /**
     *  会员停车位信息入场推送
     * @param $openid
     * @param $json
     * @param $cardNum
     */
    public static function parkingInfo($cardNum, $openid, $json)
    {
        //@to 如果为停车编号包含 10 直接查询车牌白名单
        $subParkNo = substr($json['parkingNo'],0,2);
        $subFloor = $json['floor'];
        //@if 如果查询的车牌存在在白名单中。 则入场推送
        //$allowNames = self::db()->get('ims_park_floor10_test', '*', array( 'platenumber' => $cardNum));

        //if(empty($allowNames)){
        //    return null;
        //}

        //$msg = '您幸运地成为赛格国际"反向寻车"功能的测试专员，点击详情认真填写此问卷调查，感谢您的支持和参与。';
        //$msg = "点击详情，查看您的爱车信息及车位地图，如有疑问，请拨打服务热线 029-86300000";
        $msg = "寻车图可点击详情";
        $msg_color ='#FFFFFF';
        if( date('Ymd') < '20171003' && date('Ymd') >= '20170930'){
            $msg ="\n即日起至1F赛格兰蔻专柜，独享全城最优礼遇，更有机会获得吴尊亲笔签名明星礼盒";
            $msg_color ='#000000';
        }

        /**
         * 判断数据接口反馈位置是否已经推送成功。 如果是发送过的数据不在再进行接口处理
         * ims_parkinfo_status
         * id                   PRIMARY_KEY
         * platenumber          varchar
         * parkno               varchar
         * create_time          int
         */

        //停车信息检测组件
        $eloquence = new Eloquence();

        /* 检测接口调用地址存储停车位置， 如果已经存在的话不发送数据 */
        /**
         * 车辆停车信息存储：
        1. 由立方的数据库信息识别，入场信息，如果数据存在，则建立存储标识符， （上下1小时内）
        2. 检查条件：
        2-1 ： 当天时间范围内，同一车牌号码， 同一车位信息
        2-2 ： 立方无离场记录
        查询条件1,2 均满足的话，存储数据信息（存储标识符存在的话）记录插入时的insert_ID

        车辆信息推送：
        如果存在 Insert_id 则发送数据，否则数据异常，记录日志
        车辆离场：
        检查立方数据库离场信息，根据车牌号码，删除对应的存储的Insert_ID 数据
         */

        // 入场标识符(入场时间)
        $entryIdentifier = $eloquence->searchEntryRecord($cardNum, 0);
        if($entryIdentifier){
            $parkInfoStatus = $eloquence->filterCond($cardNum,$json['parkingNo'], $entryIdentifier['create_time']);
            //$exitRecord = $eloquence->exitRecordCond($cardNum, $entryIdentifier);
            if(empty($parkInfoStatus[0])){
                $data = array(
                    'platenumber' => $cardNum,
                    'parkno'      => $json['parkingNo'],
                    'park_img'    => $json['parkingImg'],
                    'create_time' => time()
                );

                $insert_id = $eloquence->eloquenceIn($data);

                $send_data = array(
                    'platenumber' => $cardNum,
                    'issent'      => 1,
                    'create_time' => time(),
                    'format_time' => date('Y-m-d H:i:s')
                );

                $insert_sent = self::db()->insert('ims_parksent_info', $send_data);
            }else{
                return null;
            }
        }else{
            return null;
        }


        /*$day_start = mktime(0,0,0,date("m"),date("d"),date("Y"));
        $day_end   = mktime(23,59,59,date("m"),date("d"),date("Y"));


        $parkNoStatus = self::db()->select('ims_parkinfo_status', 'parkno',
            array('AND' => array('platenumber'=> $cardNum, 'parkno' =>  $json['parkingNo'],
                'create_time[<>]' => array($day_start, $day_end))),
            array('ORDER'=> 'create_time DESC ')
        );

        if(empty($parkNoStatus)){
            $data = array(
                'platenumber' => $cardNum,
                'parkno'      => $json['parkingNo'],
                'park_img'    => $json['parkingImg'],
                'create_time' => time()
            );
            $insert_id = self::db()->insert('ims_parkinfo_status', $data);
        }else{
            return null;
        }*/


        $day_start = mktime(0,0,0,date("m"),date("d"),date("Y"));
        $day_end   = mktime(23,59,59,date("m"),date("d"),date("Y"));

        /**
         * 如果当前满足停车推送的车辆在入场记录中，则查询数据推送
         */
        $inTime = self::db()->select('ims_park_entry', 'entry_time',
            array( 'AND' => array('create_time[<>]'=> array($day_start, $day_end), 'platenumber' =>$cardNum)),
            array('ORDER'=> 'create_time DESC ')
        );


        $inTimes = $inTime[count($inTime)-1];

        $inTime = substr($inTime, 10, 9);


        if(11 == $subFloor){
            $sendData = '您的爱车在11楼';
            $msg = "如有疑问，请拨打服务热线 029-86300000";
        }else{

            $token = md5(uniqid(rand(), TRUE));
            $area = self::db()->get('ims_park_are', array('zone_name','floor'), array('parkno'=>$json['parkingNo']));
            $parkInfo = substr($json['parkingNo'],3);
            $sendData = $area['floor'].'楼'.$area['zone_name'];
        }


        $data   = array(
            'touser'      => $openid['openid'],
            'template_id' => self::P_PARKING,
            //'url'         => 'http://wx.cnsaga.com/app/index.php?i=4&c=entry&do=pospay&m=member&parkingNo='.$json['parkingNo'].'&parkArea='.$json['parkArea'].'&floor='.$json['floor'].'&img='.$json['parkingImg'],
            'url'         => 'http://wx.cnsaga.com/app/index.php?i=4&c=entry&do=ParkPay&m=member&type=3&token='.$token,
            //'url'=>'',
            //'url'         => 'http://wx.sagabuy.com/app/index.php?i=4&c=entry&do=ParkPay&m=member&type=3&token='.$token,
            'data'        => array(
                'first'    => array(
                    //'value' => "您好！{$openid['realname']}，欢迎光临赛格国际购物中心，您的爱车 {$cardNum} 在这里等您，祝您购物愉快！\n",
                    'value' => "{$cardNum} \n",
                    'color' => '#000000'
                ),
                'keyword1' => array(
                    'value' => $sendData,
                    //'value' => $area['floor'].'楼'.$area['zone_name']. $parkInfo ."车位",
                    'color' => '#69008C'
                ),

                'keyword2' => array(
                    'value' => $inTimes,
                    //'value' => '8:55:10',
                    'color' => '#000000'
                ),

                'remark'   => array(
                    'value' => $msg,
                    'color' => $msg_color
                ),
            )
        );

        if($sendData == '您的爱车在11楼'){
            unset($data['url']);
        }

        /**
         * 更新发送状态
         */
        if(!empty($openid['openid'])){
            if(!empty($insert_id)){
                $updateId = self::db()->update('ims_parkinfo_status', array('issent'=> 1), array( 'id'=> $insert_id));
            }
        }

        logs(json_encode($data), 'PARKING_MSG');
        return json_encode($data);
    }




    /**
     * 会员入场
     *
     * @param $openid
     * @param $json
     *
     * @return string
     */
    private static function entry($openid, $json)
    {
        $cardSn = self::getCardInfo($openid['uid']);
        // 获取停车专用积分
        $parkScore = Park::getUser($openid['uid']);
        $parkScore = (empty($parkScore) || empty($parkScore['score'])) ? 0 : $parkScore['score'];

        // 获取会员卡积分
        $score = self::soapLink()->getCustomerScore($cardSn['custid']);
        $score = !empty($score) ? $score : 0;


        /**
         * @step1 查询是否未内部测试用户车牌
         *
         * @step2 存储测试数据车辆入场
         */

        // 积分总和
        $score = $score+$parkScore;

        if(date('Ymd') <= '20160113'){
            $msg = '【抢优惠券】鲜果时间、薯小帅、宽窄巷等人气美食1元抢 吃货侠喊你来“打劫” ';
            $url = 'http://wx.cnsaga.com/app/index.php?i=4&c=entry&do=Showentry&m=member&sagafrom=pyq';
        }else{
            if ($score < 300) {
                $msg = "您有".$score."积分，不足300分无法抵用停车费。客服电话：029-86300000\n\n";
            } else {
                $hour = floor($score/300);
                $msg = "您有".$score."积分，可抵用".$hour."小时停车费。客服电话：029-86300000\n\n";
            }
            $url = '';
        }



        /**
        if ($score < 300) {
        $msg = "您有".$score."积分，不足300分无法抵用停车费。客服电话：029-86300000\n\n";
        } else {
        $hour = floor($score/300);
        $msg = "您有".$score."积分，可抵用".$hour."小时停车费。客服电话：029-86300000\n\n";
        }
         */





        /*if ($score < 300) {
            $msg = "您有 {$score} 积分，其中包含停车专用积分 {$parkScore} ,您无法享受积分抵用停车时长，欢迎您消费后获取积分享受积分停车服务，或离场取车前至中央缴费处交费，避免出车口拥堵。\n\n";
            $msg .= "赛格会员购物时报手机号码即可积分，无须实体卡；小积分大用途，赛格积分可抵扣停车费。\n\n";
            $msg .= "客服电话：029-86300000";
        }

        if ($score >= 300 && $score < 900) {
            $hour = floor($score/300);
            $msg = "您有 {$score} 积分，其中包含停车专用积分 {$parkScore} ,仅可用积分抵用 {$hour} 小时停车时长 ，欢迎您消费后获取积分享受积分停车服务，或离场取车前至中央缴费处交费，避免出车口拥堵。\n\n";
            $msg .= "赛格会员购物时报手机号码即可积分，无须实体卡；小积分大用途，赛格积分可抵扣停车费。\n\n";
            $msg .= "客服电话：029-86300000";
        }

        if ($score >= 900 && $score < 7200) {
            $hour = floor($score/300);
            $msg = "您有 {$score} 积分，其中包含停车专用积分 {$parkScore} ,可用积分抵用 {$hour} 小时停车时长。\n";
            $msg .= "赛格会员购物时报手机号码即可积分，无须实体卡；小积分大用途，赛格积分可抵扣停车费。\n\n";
            $msg .= "客服电话：029-86300000";
        }

        if ($score >= 7200) {
            $msg = "您有 {$score} 积分，其中包含停车专用积分 {$parkScore} ,积分充足，可畅享积分停车服务。\n";
            $msg .= "赛格会员购物时报手机号码即可积分，无须实体卡；小积分大用途，赛格积分可抵扣停车费。\n\n";
            $msg .= "客服电话：029-86300000";
        }*/


        //先查询白名单数据查询
        //@to 根据openid['platenumber']
        //@if    白名单中数据存在的话, 修改msg ,url
        //$allowNames = self::db()->get('ims_park_floor10_test','*', array('platenumber' => $openid['platenumber']));

        /*if(!empty($allowNames)){
            $data = array();

            $data['mobile']      = $openid['mobile'];
            $data['platenumber'] = $openid['platenumber'];
            $data['create_time'] = time();

            $insert_id = self::db()->insert('ims_park_entry_test',$data);


            //$msg = "您幸运地成为赛格国际\"反向寻车\"功能的测试专员，点击详情认真填写此问卷调查，感谢您的支持和参与。";
            //$token = md5(uniqid(rand(), TRUE));
            //$url = 'http://wx.cnsaga.com/app/index.php?i=4&c=entry&do=survey&m=member&token='.$token;
        }else{
            //$url = 'http://wx.cnsaga.com/app/index.php?i=4&c=entry&do=parkpay&m=member';
        }*/



        //$url = 'http://wx.cnsaga.com/app/index.php?i=4&c=entry&do=parkpay&m=member';
        //@else

        $customer = self::getCustomer();
        //添加车牌日志记录
        $isSeniorMember = $customer->specialMemberDel($openid['platenumber'],$openid['uid']);
        $openids = $openid['openid'];

        switch ($isSeniorMember)
        {
            case 'VVVIP':

                $data   = array(
                    'touser'      => $openid['openid'],
                    'template_id' => self::P_ENTRY,
                    'url'         => $url,
                    'topcolor'    => '#69008C',
                    'data'        => array(
                        'first'    => array(
                            'value' => "尊敬的高级会员，感谢您光临赛格国际购物中心。\n",
                            'color' => '#000000'
                        ),
                        'keyword1' => array(
                            'value' => $openid['mobile'].' （手机号码）',
                            'color' => '#69008C'
                        ),
                        'keyword2' => array(
                            'value' => $openid['platenumber'],
                            'color' => '#69008C'
                        ),
                        'keyword3' => array(
                            'value' => $json['entryTime'] . "\n",
                            'color' => '#69008C'
                        ),
                        'remark'   => array(
                            'value' => $msg,
                            'color' => '#000000'
                        ),
                    )
                );

                break;
            default:
                $data   = array(
                    'touser'      => $openid['openid'],
                    'template_id' => self::P_ENTRY,
                    'url'         => $url,
                    'topcolor'    => '#69008C',
                    'data'        => array(
                        'first'    => array(
                            'value' => "您好！{$openid['realname']}，欢迎光临赛格国际购物中心。\n",
                            'color' => '#000000'
                        ),
                        'keyword1' => array(
                            'value' => $openid['mobile'].' （手机号码）',
                            'color' => '#69008C'
                        ),
                        'keyword2' => array(
                            'value' => $openid['platenumber'],
                            'color' => '#69008C'
                        ),
                        'keyword3' => array(
                            'value' => $json['entryTime'] . "\n",
                            'color' => '#69008C'
                        ),
                        'remark'   => array(
                            'value' => $msg,
                            'color' => '#000000'
                        ),
                    )
                );
        }




        if(!empty($openid)){
            $updateId = self::db()->update('ims_park_entry', array('issent'=> 1),
                array(
                    'AND' =>
                        array(
                            'entry_time'  => $json['entryTime'],
                            'platenumber' => $openid['platenumber']
                        )
                ));
        }

//        return json_encode($data);
        // 对于抵扣时间小于 5小时的顾客推送模板消息

        if($score < 1500){
            return json_encode($data);
        }else{
            return 'match fail';
        }
        //return json_encode($data);
    }


    /**
     * 会员离场
     *
     * @param $openid
     * @param $json
     *
     * @return string
     */
    private static function leave($openid, $json)
    {
        $cardsn  = self::getCardInfo($openid['uid']);
        // 获取停车专用积分
        $parkScore = Park::getUser($openid['uid']);
        $parkScore = (empty($parkScore) || empty($parkScore['score'])) ? 0 : $parkScore['score'];

        // 获取会员卡积分
        $score   = self::soapLink()->getCustomerScore($cardsn['custid']);
        $scores  = empty($score) ? 0 : $score;

        // 积分总和
        $scores = $scores+$parkScore;

        // 使用积分抵扣金额
        $balance = $json['score'] / 100;

        // 用户所有积分可抵用时长
        $hour = floor($scores / 300);

        // 将时长转为时分格式
        /*if ($json['duration'] > 0) {
            list($hours,$minute) = explode('.',$json['duration']);
            $minutes = round(('0.'.$minute)*60);
        } else {
            $hours = 0;
            $minutes = 0;
        }*/

        $hours = $json['amount']/3;

        //$msg = "您停车时长为".$hours."小时，共".$json['amount']."元，已使用".$json['score']."积分抵扣".$balance."元。剩余".$scores."积分，还可抵".$hour."小时。客服电话：029-86300000\n\n";
        /**
         * 微信委托代扣积分模板消息发送修正
         * @var Ambiguous $msg
         */
        $upDeclineTime   = time() + 100;
        $downDeclineTime = time() - 100;

        $papDataQuery = "SELECT `pay`,`erpscore`,`parkscore` FROM `ims_park_logs` WHERE `platenumber`= '".$openid['platenumber']."' AND `create_time` <= ".$upDeclineTime." AND `create_time` >= ".$downDeclineTime;

        $papRecordInfo = self::db()->query($papDataQuery)->fetchAll();
        $papRecordInfo = $papRecordInfo[0];

        $consume = intval($papRecordInfo['erpscore']) + intval($papRecordInfo['parkscore']);
        $balance = $consume / 100;

        if (0 == intval($papRecordInfo['pay'])) {
            $msg = "您停车时长为".$hours."小时，共".$json['amount']."元，已使用".$consume."积分抵扣".$balance."元。剩余".$scores."积分，还可抵".$hour."小时。客服电话：029-86300000\n\n";
        }else{
            $msg = "您停车时长为".$hours."小时，共".$json['amount']."元，微信委托代扣".intval($papRecordInfo['pay'])."元，已使用".$consume."积分抵扣".$balance."元。剩余".$scores."积分，还可抵".$hour."小时。客服电话：029-86300000\n\n";
        }


        if(date('Ymd') <= '20160113'){
            $url = 'http://wx.cnsaga.com/app/index.php?i=4&c=entry&do=Showentry&m=member&sagafrom=pyq';
        }else{
            $url = '';
        }


        $customer = self::getCustomer();
        $isSeniorMember = $customer->specialMemberDel($openid['platenumber'],$openid['uid']);
        $openids=$openid['openid'];
        switch ($isSeniorMember) {
            case 'VVVIP':
                $data = array(
                    'touser' => $openid['openid'],
                    'template_id' => self::P_LEAVE,
                    //'url'         => '',
                    'url' => $url,
                    'topcolor' => '#69008C',
                    'data' => array(
                        'first' => array(
                            'value' => "尊敬的高级会员，感谢您光临赛格国际购物中心。您的爱车已驶离停车场。\n",
                            'color' => '#000000'
                        ),
                        'keyword1' => array(
                            'value' => $openid['mobile'] . ' （手机号码）',
                            'color' => '#69008C'
                        ),
                        'keyword2' => array(
                            'value' => $openid['platenumber'],
                            'color' => '#69008C'
                        ),
                        'keyword3' => array(
                            'value' => $json['leaveTime'] . "\n",
                            'color' => '#69008C'
                        ),
                        'remark' => array(
                            'value' => "本次停车免费，欢迎再次光临！",
                            'color' => '#000000'
                        ),
                    )
                );

                break;
            default:
                $data    = array(
                    'touser'      => $openid['openid'],
                    'template_id' => self::P_LEAVE,
                    //'url'         => '',
                    'url'         => $url,
                    'topcolor'    => '#69008C',
                    'data'        => array(
                        'first'    => array(
                            'value' => "您好！{$openid['realname']}，感谢光临赛格国际购物中心。您的爱车已驶离停车场。\n",
                            'color' => '#000000'
                        ),
                        'keyword1' => array(
                            'value' => $openid['mobile'].' （手机号码）',
                            'color' => '#69008C'
                        ),
                        'keyword2' => array(
                            'value' => $openid['platenumber'],
                            'color' => '#69008C'
                        ),
                        'keyword3' => array(
                            'value' => $json['leaveTime'] . "\n",
                            'color' => '#69008C'
                        ),
                        'remark'   => array(
                            'value' => $msg,
                            'color' => '#000000'
                        ),
                    )
                );
        }




        // 车辆离场之后删除停车信息

        // 停车信息组件
        //$eloquence = new Eloquence();

        //$delete_id = $eloquence->wipeEloquence($openid['platenumber']);



        /* edit by dv  判断用户出场信息，避免重复推送  */
        if($json['score'] == 0){
            $carLeaveMess = self::getCarLeaveMess($openid['platenumber']);
            if($carLeaveMess){
                return false;
            }
        }

        return json_encode($data);
    }

    public static function scoreConsume($data)
    {
        $temp    = array(
            'touser'      => $data['openid'],
            'template_id' => self::S_CONSUME,
            'url'         => 'http://wx.cnsaga.com/app/index.php?i=4&c=entry&eid=1',
            'topcolor'    => '#69008C',
            'data'        => array(
                'first'    => array(
                    'value' => "您好！{$data['realname']}，感谢成为赛格国际购物中心会员。您的积分信息如下:\n",
                    'color' => '#000000'
                ),
                'keyword1' => array(
                    'value' => $data['realname'],
                    'color' => '#69008C'
                ),
                'keyword2' => array(
                    'value' => $data['mobile'].' （手机号码）',
                    'color' => '#69008C'
                ),
                'keyword3' => array(
                    'value' => "感谢您成为赛格国际购物中心会员，赠送您的 1000 停车专用积分已到帐，可点击至会员中心查看\n",
                    'color' => '#000000'
                ),
                'remark'   => array(
                    'value' => "如有疑问，请拨打客服电话：029-86300000",
                    'color' => '#000000'
                ),
            )
        );
        return json_encode($temp);
    }

    public static function  sendCard($openid,$amount,$time,$cardSn,$mobile)
    {

        $url = 'http://p.sagabuy.com/checkOrder.php?checkmsg='.md5("水单信息核对" . date('Y-m-d')).'&type=3&memCard='.$cardSn.'&orderTime='.$time.'&price='.$amount;
        $order    = file_get_contents($url);
        $order = json_decode($order,true);

        if ($order['status'] == 1 && !empty($order['orderList'])) {
            foreach ($order['orderList'] as $orderId => $orderInfo) {
                // 判断价格是否在区间范围
                $orderPrice = $amount;
                if ($orderPrice < 500) {
                    continue;
                }

                // 判断流水号是否重复领取
                $checkCard = self::db()->get('card_card_card','password',array('orderid'=>$orderId));

                if ($checkCard) {
                    continue;
                }

                // 获取商户名称
                $deptId = $orderInfo['deptId'];
                $brand = self::db()->get('card_dept','brand',array('c_dept_id'=>$deptId));
                if (empty($brand)) {
                    continue;
                }
                // 优惠券金额
                $cardPrice = floor($orderPrice/500)*50;

                // 领卡
                $password = self::db()->get('card_card_card','password',array('status'=>1));

                if ($password) {
                    $data = array(
                        'price'      => $cardPrice,
                        'tel'        => $mobile,
                        'openid'     => $openid,
                        'orderid'    => $orderId,
                        'c_dept_id'  => $deptId,
                        'brand'      => $brand,
                        'start_time' => date('Y-m-d', strtotime('+1 day', strtotime($order['dateTime']))),
                        'end_time'   => '2015-10-31',
                        'orderPrice' => $orderPrice,
                        'status' => 2,
                        'r_way'      => 1
                    );
                    $result = self::db()->update('card_card_card',$data,array('password'=>$password));

                    if ($result) {
                        $temp    = array(
                            'touser'      => $openid,
                            'template_id' => 'NeJT0MzlrbnEO9fL0x5zmTXzbUeq5vQCyGCtti_p52E',
                            'url'         => 'http://wx.cnsaga.com/app/index.php?i=4&c=entry&do=coupons&m=member',
                            'topcolor'    => '#69008C',
                            'data'        => array(
                                'first'    => array(
                                    'value' => "恭喜您成功领取 {$cardPrice} 元 {$brand} 电子券一张。\n",
                                    'color' => '#000000'
                                ),
                                'keyword1' => array(
                                    'value' => '电子券',
                                    'color' => '#69008C'
                                ),
                                'keyword2' => array(
                                    'value' => $password,
                                    'color' => '#69008C'
                                ),
                                'keyword3' => array(
                                    'value' => date('Y-m-d', strtotime('+1 day', strtotime($orderInfo['date']))),
                                    'color' => '#69008C'
                                ),
                                'keyword4' => array(
                                    'value' => "2015-10-31\n",
                                    'color' => '#69008C'
                                ),
                                'remark'   => array(
                                    'value' => "如有疑问，请拨打客服电话：029-86300000",
                                    'color' => '#000000'
                                )
                            )
                        );
                        Wechat::sendTemplateMessage(json_encode($temp));
                    }
                }
            }
        }
    }

}